package org.leetcode.middle.leetcode54;


import java.util.ArrayList;
import java.util.List;

public class Solution
{
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> list = new ArrayList<>();

        int i,j;

        int loop=0;

        int x = matrix[0].length;
        int y = matrix.length;

        int count =0;

        int start = 0;

        int min = Math.min(x, y);

        while (loop++<min/2)
        {
            for (i=start;i<x-loop;i++)
            {
                list.add(matrix[start][i]);
                count++;
            }

            for (j=start;j<y-loop;j++)
            {
                list.add(matrix[j][i]);
                count++;

            }

            for (;i>=loop;i--)
            {
                list.add(matrix[j][i]);
                count++;

            }

            for (;j>=loop;j--)
            {
                list.add(matrix[j][i]);
                count++;
            }

            start++;
        }

        if (count==x*y)
        {
            return list;
        }

        if (x==y && x/2==1 )
        {
            list.add(matrix[start][start]);
            return list;
        }


        int plusNumber = x*y-count;

        int temp =start;

        if (x>y)
        {
            while (plusNumber!=0)
            {
                plusNumber--;

                list.add(matrix[temp][start++]);

            }

        }else {
            while (plusNumber!=0)
            {
                plusNumber--;

                list.add(matrix[start++][temp]);
            }
        }


        return list;
    }

    public static void main(String[] args) {
        int [] [] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

        Solution solution  = new Solution() ;

        List<Integer> list = solution.spiralOrder(matrix);


    }
}
